package test;

import com.hkx.hbn.demo.entity.Clazz;
import com.hkx.hbn.demo.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Set;

public class HbnTest2 {
    private Session session;//最核心的接口，操作数据库的

    @Before
    public void before() {
        //获取Session 对象的步骤
//        1. 读取配置文件
        Configuration configuration = new Configuration().configure("com/hkx/hbn/demo/config/hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        session = sessionFactory.openSession();
        session.getTransaction().begin();
        //sessionFactory.getCurrentSession();

    }

    @After
    public void after() {
        session.getTransaction().commit();
    }

    /*
    测试 one-to-many
     */
    @Test
    public void test1() {
        Student student1 = new Student("黄六", "6666");
        Student student2 = new Student("黄鱼", "8888");
        Clazz clazz = new Clazz().setName("JAVA 1班");
        student1.setClazz(clazz);
        student2.setClazz(clazz);
        session.save(clazz);
        session.save(student1);
        session.save(student2);
    }

    @Test
    public void test3() {
        Student student = session.get(Student.class, "4028818578623b190178623b1c020002");
        System.out.println(student.getName() + "->"+student.getClazz().getName());
    }

    @Test
    public void test4() {
        Clazz clazz = session.get(Clazz.class, "4028818578623b190178623b1be80000");
        System.out.println(clazz.getName());
        Set<Student> students = clazz.getStudents();
        for (Student student : students) {
            System.out.println(student);
        }

    }




}
